<?php

/**
 * Yii Controller HeaderController
 *
 * @author nguyenmanhluu
 * @since Aug 14, 2013 - 3:35:52 PM
 */
class HeaderController extends FrontElementController
{

    public $optsCate = 'Header';

    public function actionIndex()
    {
        parent::actionIndex();

        if ($this->_uploadDefaultGallery() && $this->_deletedGallery() && $this->_writeRobotsFile())
        {
            Yii::app()->request->redirect(Yii::app()->createUrl('header/index'));
        }
    }

    protected function _uploadDefaultGallery()
    {
        $dir     = 'bizGal';
        $fileKey = 'galleryImage';
        if (@$_FILES[$fileKey])
        {
            foreach ($_FILES[$fileKey]['name'] as $fkey => $fname)
            {
                // Lấy extension của file và tạo tên file mới
                $ext        = pathinfo($fname, PATHINFO_EXTENSION);
                $image_file = "files/$dir/" . md5(time() . $fname) . ".$ext";
                $thumb_file = "files/$dir/" . md5(time() . $fname) . "_.$ext";

                // Move file vào thư mục cần lưu                
                if (@move_uploaded_file($_FILES[$fileKey]['tmp_name'][$fkey], $image_file))
                {
                    // Resize ảnh
                    $thumb = Yii::app()->phpThumb->create($image_file);
                    $thumb->save($thumb_file);

                    // Lưu vào csdl
                    $si             = new BusinessGallery();
                    $si->image      = $image_file;
                    $si->thumbnail  = $thumb_file;
                    $si->is_default = BusinessGallery::IS_DEFAULT;
                    $si->save();
                }
            }
            return TRUE;
        }
    }

    protected function _deletedGallery()
    {
        if (isset($_POST['deleteGallery']))
        {
            foreach ($_POST['deleteGallery'] as $galleryId)
            {
                $gallery = BusinessGallery::model()->findByPk($galleryId);
                if ($gallery != null)
                {
                    @unlink($gallery->image);
                    BusinessGallery::model()->deleteByPk($galleryId);
                }
            }
        }

        return TRUE;
    }

    protected function _writeRobotsFile()
    {
        if (isset($_POST['robots']))
        {
            $file = 'robots.txt';
            if (file_exists($file))
            {
                $fh  = fopen($file, 'w');
                $val = $_POST['robots'];
                fwrite($fh, $val);
                fclose($fh);
            }
        }
        return TRUE;
    }

}

/** 
 * End file HeaderController
 */